import { forwardRef, ReactElement, useImperativeHandle, useState } from 'react'
import { Modal } from 'antd'

export const commonModalStyle = {
  width: '50vw'
}

const CommonModal = forwardRef(
  (
    {
      children,
      onOk,
      onCancel,
      title,
      onOpen
    }: { children: ReactElement; onOk: () => Promise<boolean> | boolean | void; onCancel: () => void; title: string; onOpen?: () => void },
    ref
  ) => {
    const [open, setOpen] = useState(false)

    const showModal = () => {
      setOpen(true)
      onOpen?.()
    }
    const handleOk = () => {
      const doneOk = onOk()

      Promise.resolve(doneOk ?? true).then((isOk) => {
        if (isOk) {
          setOpen(false)
        }
      })
    }

    const handleCancel = () => {
      setOpen(false)
      onCancel()
    }

    useImperativeHandle(ref, () => ({
      showModal
    }))

    return (
      <Modal {...commonModalStyle} open={open} title={title} onCancel={handleCancel} onOk={handleOk}>
        {children}
      </Modal>
    )
  }
)

export default CommonModal
